package com.example.employeejdbc.dao;

import com.example.employeejdbc.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class EmployeeDaoImpl extends JdbcDaoSupport implements EmployeeDao {
    @Autowired
    DataSource dataSource;

    @PostConstruct
    private void initialize(){
        setDataSource(dataSource);
    }

    @Override
    public List<Employee> getAllEmployees() {
        List<Employee> employees = new ArrayList<>();
        String sql = "select * from employee";
        List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql);
        for (Map<String, Object> row : rows) {
            Employee employee = new Employee();
            employee.setEmpId((int) row.get("empId"));
            employee.setEmpName((String) row.get("empName"));
            employees.add(employee);
        }
        return employees;
    }

    @Override
    public void insertEmployee(Employee employee) {
        String sql = "insert into employee(empId, empName) values(?,?)";
        getJdbcTemplate().update(sql, employee.getEmpId(), employee.getEmpName());
    }
}
